package com.weijian.bizmq;

import com.rabbitmq.client.Channel;
import com.weijian.dal.entity.ImageAI;
import com.weijian.dal.enums.ImageStatusEnum;
import com.weijian.service.ImageAIService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.ai.image.ImageModel;
import org.springframework.ai.image.ImagePrompt;
import org.springframework.ai.image.ImageResponse;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

@Component
@Slf4j
@RequiredArgsConstructor
public class MyMessageConsumer {

    final ImageAIService imageAIService;

    final ImageModel imageModel;

    /**
     * 接收消息的方法
     *
     * @param message     接收到的消息内容，是一个字符串类型
     * @param channel     消息所在的通道，可以通过该通道与 RabbitMQ 进行交互，例如手动确认消息、拒绝消息等
     * @param deliveryTag 消息的投递标签，用于唯一标识一条消息
     */
    /*@SneakyThrows
    @RabbitListener(queues = {"code_queue"}, ackMode = "MANUAL")
    public void receiveMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        log.info("receiveMessage message = {}", message);
        channel.basicAck(deliveryTag, false);
    }*/
    @SneakyThrows
    @RabbitListener(queues = {MqConstant.QUEUE_NAME}, ackMode = "MANUAL")
    public void receiveMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        log.info("receiveMessage message = {}", message);
        if (StringUtils.isBlank(message)) {
            // 如果失败，消息拒绝
            channel.basicNack(deliveryTag, false, false);
            throw new RuntimeException("消息为空");
        }
        long ImageAIId = Long.parseLong(message);
        ImageAI ImageAI = imageAIService.getById(ImageAIId);
        if (ImageAI == null) {
            channel.basicNack(deliveryTag, false, false);
            throw new RuntimeException("图片为空");
        }
        // 先修改任务状态为 “执行中”。等执行成功后，修改为 “已完成”、保存执行结果；执行失败后，状态修改为 “失败”，记录任务失败信息。
        ImageAI updateImageAI = new ImageAI();
        updateImageAI.setId(ImageAI.getId());
        updateImageAI.setStatus(ImageStatusEnum.PROCESSING.getValue());
        boolean b = imageAIService.updateById(updateImageAI);
        if (!b) {
            channel.basicNack(deliveryTag, false, false);
            handleImageAIUpdateError(ImageAI.getId(), "更新图表执行中状态失败");
            return;
        }
        // 调用 AI
        ImageResponse imageResponse = imageModel.call(new ImagePrompt(ImageAI.getUserPrompt()));
        ImageAI updateImageAIResult = new ImageAI();
        updateImageAIResult.setId(ImageAI.getId());
        updateImageAIResult.setImgUrl(imageResponse.getResult().getOutput().getUrl());
        updateImageAIResult.setStatus(ImageStatusEnum.SUCCESS.getValue());
        boolean updateResult = imageAIService.updateById(updateImageAIResult);
        if (!updateResult) {
            channel.basicNack(deliveryTag, false, false);
            handleImageAIUpdateError(ImageAI.getId(), "更新图表成功状态失败");
        }
        // 消息确认
        channel.basicAck(deliveryTag, false);
    }

    /**
     * 构建用户输入
     *
     * @param
     * @return
     */
    /*private String buildUserInput(ImageAI imageAI) {
        String goal = imageAI.getGoal();
        String ImageAIType = imageAI.getImageAIType();
        String csvData = imageAI.getImageAIData();

        // 构造用户输入
        StringBuilder userInput = new StringBuilder();
        userInput.append("分析需求：").append("\n");

        // 拼接分析目标
        String userGoal = goal;
        if (StringUtils.isNotBlank(ImageAIType)) {
            userGoal += "，请使用" + ImageAIType;
        }
        userInput.append(userGoal).append("\n");
        userInput.append("原始数据：").append("\n");
        userInput.append(csvData).append("\n");
        return userInput.toString();
    }*/
    private void handleImageAIUpdateError(long ImageAIId, String execMessage) {
        ImageAI updateImageAIResult = new ImageAI();
        updateImageAIResult.setId(ImageAIId);
        updateImageAIResult.setStatus(ImageStatusEnum.FAIL.getValue());
        updateImageAIResult.setExecMessage("execMessage");
        boolean updateResult = imageAIService.updateById(updateImageAIResult);
        if (!updateResult) {
            log.error("更新图表失败状态失败" + ImageAIId + "," + execMessage);
        }
    }

}
